<template>
  <div class="business-scenario-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="goBack"
          class="back-button"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="header-content">
          <h1 class="page-title">业务场景库</h1>
          <p class="page-subtitle">管理所有业务场景下的知识库内容</p>
        </div>
      </div>
      <el-button type="primary" @click="handleAdd" class="add-btn">
        + 新增业务场景
      </el-button>
    </div>

    <!-- 业务场景卡片列表 -->
    <div class="scenario-grid">
      <div 
        v-for="scenario in scenarioList" 
        :key="scenario.id"
        class="scenario-card"
        :class="{ 'loading-card': scenario.loading, 'disabled-card': !scenario.clickable }"
        @click="handleScenarioClick(scenario)"
      >
        <div class="card-header">
          <div class="icon-wrapper">
            <el-icon :size="24" :color="scenario.iconColor">
              <component :is="scenario.icon" />
            </el-icon>
            <!-- 加载状态指示器 -->
            <div v-if="scenario.loading" class="loading-indicator">
              <el-icon class="rotating">
                <Loading />
              </el-icon>
            </div>
          </div>
          <h3 class="scenario-name">{{ scenario.name }}</h3>
          <!-- 状态标签 -->
          <el-tag 
            v-if="scenario.status === 'processing'" 
            type="warning" 
            size="small"
            class="status-tag"
          >
            解析中
          </el-tag>
          <el-tag 
            v-else-if="scenario.status === 'completed'" 
            type="success" 
            size="small"
            class="status-tag"
          >
            已完成
          </el-tag>
        </div>
        
        <p class="scenario-description">{{ scenario.description }}</p>
        
        <div class="card-footer">
          <div class="update-info">
            <el-icon :size="14" color="#909399">
              <Clock />
            </el-icon>
            <span class="update-time">{{ scenario.updateTime }}</span>
          </div>
          <el-button 
            type="text" 
            size="small" 
            @click.stop="handleEdit(scenario)"
            class="edit-btn"
          >
            编辑
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="scenarioList.length === 0" class="empty-state">
      <el-empty description="暂无业务场景">
        <el-button type="primary" @click="handleAdd">创建第一个业务场景</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, 
  Document, 
  School, 
  Reading, 
  Collection, 
  User, 
  Clock, 
  Loading,
  Warning
} from '@element-plus/icons-vue'

export default {
  name: 'BusinessScenarioDetail',
  setup() {
    const router = useRouter()
    const route = useRoute()

    // 业务场景列表数据
    const scenarioList = ref([
      {
        id: 1,
        name: '学区政策知识库',
        description: '包含各地区学区划分政策、入学条件、申请流程等相关信息',
        updateTime: '2024-01-15 14:30',
        icon: 'School',
        iconColor: '#409EFF',
        status: 'completed',
        clickable: true
      },
      {
        id: 2,
        name: '学校招生指南',
        description: '各类学校招生简章、报名要求、考试安排等招生相关信息',
        updateTime: '2024-01-14 16:45',
        icon: 'Reading',
        iconColor: '#67C23A',
        status: 'completed',
        clickable: true
      },
      {
        id: 3,
        name: '教育资源库',
        description: '教学资料、课程信息、师资力量等教育资源相关内容',
        updateTime: '2024-01-13 10:20',
        icon: 'Collection',
        iconColor: '#E6A23C',
        status: 'completed',
        clickable: true
      },
      {
        id: 4,
        name: '学生服务指南',
        description: '学生生活服务、校园设施、课外活动等学生服务相关信息',
        updateTime: '2024-01-12 09:15',
        icon: 'User',
        iconColor: '#F56C6C',
        status: 'completed',
        clickable: true
      }
    ])

    // 工作流完成事件监听器
    let workflowCompletionListener = null

    // 检查是否有新创建的场景需要添加
    onMounted(() => {
      const newScenarioData = route.query.newScenario
      if (newScenarioData) {
        try {
          const scenario = JSON.parse(newScenarioData)
          // 检查是否已存在相同ID的场景，避免重复添加
          const existingIndex = scenarioList.value.findIndex(s => s.id === scenario.id)
          if (existingIndex === -1) {
            // 添加新场景到列表
            const newScenario = {
              id: scenario.id,
              name: scenario.name,
              description: scenario.description,
              updateTime: new Date().toLocaleString('zh-CN'),
              icon: 'Loading',
              iconColor: '#909399',
              status: 'processing',
              clickable: false,
              workflows: scenario.workflows || [],
              loading: true,
              hasFiles: scenario.hasFiles,
              hasUrls: scenario.hasUrls,
              urlsCount: scenario.urlsCount || 0,
              filesCount: scenario.filesCount || 0
            }
            
            scenarioList.value.unshift(newScenario)
            
            // 设置工作流完成监听器
            setupWorkflowCompletionListener(newScenario)
            
            // 检查是否已经有完成的数据（防止竞态条件）
            checkExistingCompletionData(newScenario)
          }
        } catch (error) {
          console.error('解析新场景数据失败:', error)
        }
      }
    })

    // 设置工作流完成监听器
    const setupWorkflowCompletionListener = (scenario) => {
      // 监听自定义事件
      workflowCompletionListener = (event) => {
        const completionData = event.detail
        if (completionData.scenarioId === scenario.id) {
          handleWorkflowCompletion(completionData)
        }
      }
      
      window.addEventListener('workflowCompleted', workflowCompletionListener)
      
      // 同时监听localStorage变化（作为备用方案）
      const checkCompletion = () => {
        const completionKey = `workflow_completion_${scenario.id}`
        const completionData = localStorage.getItem(completionKey)
        if (completionData) {
          try {
            const data = JSON.parse(completionData)
            handleWorkflowCompletion(data)
            localStorage.removeItem(completionKey) // 清理数据
          } catch (error) {
            console.error('解析工作流完成数据失败:', error)
          }
        }
      }
      
      // 定期检查（防止事件丢失）
      const checkInterval = setInterval(checkCompletion, 2000)
      
      // 60秒后停止检查（超时处理）
      setTimeout(() => {
        clearInterval(checkInterval)
        if (scenario.status === 'processing') {
          console.warn('工作流处理超时，可能需要手动刷新')
          // 超时处理：将状态改为失败
          scenario.status = 'failed'
          scenario.loading = false
          scenario.icon = 'Warning'
          scenario.iconColor = '#F56C6C'
          ElMessage.error(`${scenario.name} 数据解析超时，请稍后重试`)
        }
      }, 60000)
    }

    // 检查是否已经有完成的数据
    const checkExistingCompletionData = (scenario) => {
      const completionKey = `workflow_completion_${scenario.id}`
      const completionData = localStorage.getItem(completionKey)
      if (completionData) {
        try {
          const data = JSON.parse(completionData)
          handleWorkflowCompletion(data)
          localStorage.removeItem(completionKey)
        } catch (error) {
          console.error('解析已存在的工作流完成数据失败:', error)
        }
      }
    }

    // 处理工作流完成
    const handleWorkflowCompletion = (completionData) => {
      const index = scenarioList.value.findIndex(s => s.id === completionData.scenarioId)
      if (index !== -1) {
        const scenario = scenarioList.value[index]
        
        // 更新场景状态
        scenario.status = completionData.status
        scenario.loading = false
        scenario.workflows = completionData.workflows || []
        
        if (completionData.status === 'completed') {
          scenario.clickable = true
          scenario.icon = 'Document'
          scenario.iconColor = '#67C23A'
          
          const successMsg = completionData.successCount > 0 
            ? `${scenario.name} 数据解析完成！成功处理 ${completionData.successCount} 项`
            : `${scenario.name} 创建完成！`
          
          if (completionData.failureCount > 0) {
            ElMessage.warning(`${successMsg}，失败 ${completionData.failureCount} 项`)
          } else {
            ElMessage.success(successMsg)
          }
        } else if (completionData.status === 'failed') {
          scenario.clickable = false
          scenario.icon = 'Warning'
          scenario.iconColor = '#F56C6C'
          ElMessage.error(`${scenario.name} 数据解析失败：${completionData.error || '未知错误'}`)
        }
        
        console.log('场景状态已更新:', scenario)
        
        // 清理localStorage中的完成数据
        const completionKey = `workflow_completion_${scenario.id}`
        localStorage.removeItem(completionKey)
      }
    }

    // 组件卸载时清理监听器
    onUnmounted(() => {
      if (workflowCompletionListener) {
        window.removeEventListener('workflowCompleted', workflowCompletionListener)
      }
    })

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 新增业务场景
    const handleAdd = () => {
      router.push('/knowledge/create-business-scenario')
    }

    // 点击场景卡片
    const handleScenarioClick = (scenario) => {
      // 检查场景是否可点击
      if (!scenario.clickable) {
        if (scenario.status === 'processing') {
          ElMessage.warning('数据正在解析中，请稍后再试')
        } else if (scenario.status === 'failed') {
          ElMessage.error('数据解析失败，请重新创建或联系管理员')
        }
        return
      }
      
      // 只有状态为completed的场景才能点击进入
      if (scenario.status !== 'completed') {
        ElMessage.warning('该场景暂不可用')
        return
      }
      
      // 跳转到场景数据详情页面，传递场景信息
      router.push({
        path: '/knowledge/scenario-data-detail',
        query: {
          id: scenario.id,
          name: scenario.name,
          tableId: scenario.tableId || 'default-table-id' // 这里需要实际的teable ID
        }
      })
    }

    // 编辑场景
    const handleEdit = (scenario) => {
      ElMessage.info(`编辑场景: ${scenario.name}`)
      // 这里可以跳转到编辑页面
    }

    return {
      scenarioList,
      goBack,
      handleAdd,
      handleScenarioClick,
      handleEdit
    }
  }
}
</script>

<style scoped>
.business-scenario-detail {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  font-size: 14px;
  margin-top: 4px;
}

.back-button:hover {
  color: #409eff;
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.add-btn {
  flex-shrink: 0;
}

.scenario-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-top: 24px;
}

.scenario-card {
  background: white;
  border-radius: 6px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e8e8e8;
  min-height: 220px;
  display: flex;
  flex-direction: column;
}

.scenario-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.icon-wrapper {
  margin-right: 8px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background: #f5f7fa;
}

.scenario-name {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 2px;
  display: inline-block;
}

.scenario-description {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  margin-bottom: 16px;
  min-height: 60px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  margin-top: auto; /* 将footer推到底部 */
}

.update-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.update-time {
  color: #c0c4cc;
  font-size: 11px;
}

.edit-btn {
  color: #409eff;
  font-size: 11px;
  padding: 2px 8px;
  background: #f0f2f5;
  border: none;
  border-radius: 3px;
}

.edit-btn:hover {
  background-color: #ecf5ff;
}

/* 加载和禁用状态样式 */
.loading-card {
  position: relative;
}

.disabled-card {
  cursor: not-allowed;
  opacity: 0.7;
}

.disabled-card:hover {
  transform: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-indicator {
  position: absolute;
  top: -5px;
  right: -5px;
  background: white;
  border-radius: 50%;
  padding: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.status-tag {
  margin-left: auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.icon-wrapper {
  position: relative;
  flex-shrink: 0;
}

.scenario-name {
  flex: 1;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .scenario-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .scenario-grid {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-left {
    width: 100%;
  }
  
  .add-btn {
    align-self: flex-end;
  }
}

:deep(.el-empty__description) {
  margin-bottom: 20px;
}
</style>